#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <time.h>
#include <string.h>

struct {
	char dest[18];
	char name[248];
} bt[100];

int main(int argc, char * argv[])
{
    int dev;

    if(argc != 2){
        printf("Usage: %s <FILENAME>\n", argv[0]);
        exit(1);
    }

    inquiry_bt();
	
    printf("Choose one to send file:  ");    
    scanf("%d",&dev);

    struct sockaddr_rc addr = { 0 };
    int s, status,i,j,k,len;
    long  size = 0;

    char buf[4096] = { 0 },sizes[100];
    char *dest = bt[dev].dest;
    FILE *fp;
    time_t start, finish,spend; 
	
    // get file size
    fp=fopen(argv[1],"rb");
    if (fp) {
      fseek(fp, 0, SEEK_END);
      size = ftell(fp);
      fclose(fp);
    }
    sprintf(sizes,   "%ld",   size);

    // allocate a socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    // set the connection parameters (who to connect to)
    addr.rc_family = AF_BLUETOOTH;
    addr.rc_channel = (uint8_t) 1;
    str2ba( dest, &addr.rc_bdaddr );

    // connect to server
    status = connect(s, (struct sockaddr *)&addr, sizeof(addr));

    // sending start
    printf("writing data...\n");
    start = time(NULL);

    // file name 
    printf("sending file %s",argv[1]);

    // sending file size
    write(s, &sizes, sizeof(sizes));
    fp=fopen(argv[1],"rb");

    // sending file content
    while(len = fread(buf, 1, 1000, fp), len > 0){
            write(s, buf, sizeof(buf));
            if(len < 1000) break;
    }


    finish = time(NULL);
    printf("\ncomplete\n");

    if( status < 0 ) perror("uh oh");
    spend = finish - start;
    printf("time spend %ld\n",spend);
    fclose(fp);	
    close(s);
    return 0;
}

int inquiry_bt()
{
    inquiry_info *ii = NULL;
    int max_rsp, num_rsp;
    int dev_id, sock, len, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };

    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }

    printf("Searching for device...  \n");    

    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));
    
    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
    if( num_rsp < 0 ) perror("hci_inquiry");
    if( num_rsp == 0){
	 perror("no device");
	 exit(1);
    }
    for (i = 0; i < num_rsp; i++) {
        ba2str(&(ii+i)->bdaddr, addr);
        memset(name, 0, sizeof(name));
        if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name), 
            name, 0) < 0)
        strcpy(name, "[unknown]");
        printf("[%d]  %s\n", i, name);
	strcpy(bt[i].dest,addr);
	strcpy(bt[i].name,name);
	}
    free( ii );
    close( sock );
    return 1;
}

